﻿// Alphabetical list of Midori Javascript Functions

$.fn.target = function() {
    return $(this[0].target) || $(this[0].srcElement);
}


AttachmentDeleted = function(anchor) {
    var value = $(anchor).next().html();
    $('.jq_deletedFileNames').val($('.jq_deletedFileNames').val() + value + '|');

    var unchangedFileNames = $('.jq_unchangedFileNames').val().split('|');
    var text = '';
    for (i = 0; i < unchangedFileNames.length; i++) {
        if (unchangedFileNames[i] != value && unchangedFileNames[i] != '') {
            text += unchangedFileNames[i] + '|';
        }
    }
    $('.jq_unchangedFileNames').val(text);
    $(anchor).parent().remove();
}

DetermineIfManageProjects = function() {
    $('.checkBoxAdmin').click(function(e) {
        $(".checkBoxAdmin input").each(function() {
            if (this.checked) {
                $(".checkBoxManageProjects input").each(function() {
                    this.checked = true;
                    $('.checkBoxManageProjects input').attr('disabled', 'disabled');
                });
            }
            else {
                $(".checkBoxManageProjects input").each(function() {
                    $('.checkBoxManageProjects input').attr('disabled', '');
                });

            }
        });
    }).click();
}

EnableAuthenticationPanels = function() {
    $('.radio').click(function(e) {
        if ($("input", $(this))[0].checked) {
            $('#ctl00_MainContent_pnlAD').css('display', '');
            $('#ctl00_MainContent_pnlForms').css('display', 'none');
        }
        else {
            $('#ctl00_MainContent_pnlAD').css('display', 'none');
            $('#ctl00_MainContent_pnlForms').css('display', '');
        }
    }).click();

}

EnableSave = function(e) {
    $(e).target().parents('.status-wrap').find('.jq_button-save').removeAttr('disabled').attr({ src: "/_layouts/images/Kiiro/button-save.png" });
}

EnableUpdateProjectSummary = function(e) {
    $(e).target().parents('.project-status-update').find('.jq_button-update').removeAttr('disabled').attr({ src: "/_layouts/images/Kiiro/button-save.png" });
}

EnableUpdateUserStatus = function(e) {
    $(e).target().parents('.activity-update').find('.jq_button-update').removeAttr('disabled').attr({ src: "/_layouts/images/Kiiro/button-save.png" });
}

FillColors = function() {
    $('.portalHeadline').val(RGBtoHex($('.portalH').css('background-color')));
    $('.portalMenu').val(RGBtoHex($('.portalM').css('background-color')));
    $('.projectHeadline').val(RGBtoHex($('.projectH').css('background-color')));
    $('.projectMenu').val(RGBtoHex($('.projectM').css('background-color')));
    $('.links').val(RGBtoHex($('.linkBG').css('background-color')));
    $('.titleColor').val(RGBtoHex($('.titleBG').css('background-color')));
    return true;
}

InitAttachments = function() {
    var url = location.pathname;

    if (url.indexOf("DisplayDiscussion") > 0) {
        $('#attachments_input').each(function() {
            var list = $(this).parent().parent().find("ul.attachments");
            $(this).MultiFile({
                STRING: {
                    icon: '<img src="/_layouts/images/Kiiro/icon-attachment.gif" alt="Attachment" />'
                },
                list: list
            });
        });

        $('.comment-details').each(function() {
            var list = $(this).children().children().find("ul.attachments");
            $(this).MultiFile({
                STRING: {
                    icon: '<img src="/_layouts/images/Kiiro/icon-attachment.gif" alt="Attachment" />'
                },
                list: list
            });
        });

        $('#my_attachments').each(function() {
            if ($('#my_attachments').parent().parent().parent().hasClass("settings")) {
                var list = $(this).find("ul.attachments");
                $(this).MultiFile({
                    STRING: {
                        icon: '<img src="/_layouts/images/Kiiro/icon-attachment.gif" alt="Attachment" />'
                    },
                    list: list
                });
            }
        });
    }
    else {
        $('#attachments_input').MultiFile({
            STRING: {
                icon: '<img src="/_layouts/images/Kiiro/icon-attachment.gif" alt="Attachment" />'
            }
        });
    }
}

InitAutoGrow = function() {
    $('.autoGrow').growfield({
        animate: false
    });
}

InitCarousel = function() {
    $('.jq_carousel').each(function() {

        var manager = $(this).parents('.manager');

        var options = {
            buttonPrevHTML: '<div style="float:left; padding-top: 66px;"><img src="/_layouts/images/Kiiro/icon-shift-left.png" style="cursor: pointer;" alt="Previous" /></div>',
            buttonPrevCallback: function(carousel, button, enabled) { $(button).css({ 'visibility': (enabled ? 'visible' : 'hidden') }); },
            buttonNextHTML: '<div style="float:right; padding-top: 66px;"><img src="/_layouts/images/Kiiro/icon-shift-right.png"  style="cursor: pointer;" alt="Next" /></div>',
            buttonNextCallback: function(carousel, button, enabled) { $(button).css({ 'visibility': (enabled ? 'visible' : 'hidden') }); },
            initCallback: function(carousel, state) { $(manager).css({ 'position': 'relative', 'top': '0', 'left': '0' }); },
            scroll: 1
        };

        var color = $(this).jcarousel(options).find('.userNameLink').css('color');

        $(this).jcarousel(options).find('.userNameLink').click(function() {
            window.location = $(this).attr('href');
        }).hover(
            function() { $(this).css({ 'color': '#1E1E1E' }) },
            function() { $(this).css({ 'color': color }) }
        );
    });
}


InitColorPickers = function() {
    MakeColorPicker('#csPortalHeadline', '.portalH');
    MakeColorPicker('#csPortalMenu', '.portalM');
    MakeColorPicker('#csProjectHeadline', '.projectH');
    MakeColorPicker('#csProjectMenu', '.projectM');
    MakeColorPicker('#csLinks', '.linkBG');
    MakeColorPicker('#csTitles', '.titleBG');
}


InitCustomForm = function() {
    $('.settings .row:last').addClass('borderless');
}


InitDatePickers = function() {
    var options = {
        buttonImage: '/_layouts/images/Kiiro/icon-datepicker.png',
        buttonImageOnly: true,
        buttonText: 'Select from calendar',
        changeMonth: true,
        changeYear: true,
        duration: '',
        dateFormat: 'mm/dd/yy',
        showOn: 'button',
        onSelect: function() { this.focus() }
    };

    $('.datepicker').not($('.readonly')).datepicker(options);
}

InitDocLibraryMoveRename = function() {

    var settings = {};

    $('.lnkMove').click(function() {

        var options = $('#pop-wrap .destinations option[value^=' + $(this).attr('path') + ']');
        var width = $('#pop-wrap .destinations').width() + 60;

        $('#pop-wrap .name, #pop-wrap .save').hide();
        $('#pop-wrap .destinations').show().removeAttr('disabled');
        $('#pop-wrap').css({ 'width': width + 'px' });

        settings = {
            anchoredSelector: '.lnkMove[docId=' + $(this).attr('docId') + ']',
            borderSize: '0',
            docId: $(this).attr('docId'),
            functionCallOnClose: function() {
                $('#pop-wrap .validation-message').hide();
                if (this.isFolder) {
                    if (this.optionIndex >= $('#pop-wrap .destinations option').length)
                        $('#pop-wrap .destinations option:last').after(this.options);
                    else
                        $('#pop-wrap .destinations option').eq(this.optionIndex).before(this.options);
                }
            },
            isFolder: $(this).attr('isFolder') == 'true',
            modal: 1,
            optionIndex: $('#pop-wrap .destinations option').index(options[0]),
            options: options.remove(),
            overlayOpacity: '50',
            positionLeft: ((width - 60) * -1),
            positionTop: -25,
            positionType: 'anchoredSingleWindow',
            windowBGColor: 'transparent',
            windowPadding: 0,
            windowSourceID: '#pop'
        };

        if ($('#pop-wrap .destinations option').length <= 1)
            $('#pop-wrap .destinations').attr('disabled', 'disabled');
            
        $('#pop-wrap h2').text(settings.isFolder ? 'Move Folder:' : 'Move File:');

        $.openDOMWindow(settings);
        return false;
    });

    $('#pop-wrap .destinations').live('change', function() {
        $('#pop-wrap .validation-message').hide();
        if ($(this).val() != '') {
            var data = {
                operationType: 'MoveFileOrFolder',
                itemId: settings.docId,
                destination: $(this).val()
            }
            MoveRenameFileOrFolder(data);
        }
    });

    $('.lnkRename').click(function() {

        var width = $('.name').width() + 60;
        
        $('#pop-wrap .name').removeAttr('disabled');
        $('#pop-wrap .name, #pop-wrap .save').show();
        $('#pop-wrap .destinations').hide();
        $('#pop-wrap').css({ 'width': width + 'px' });

        settings = {
            anchoredSelector: '.lnkRename[docId=' + $(this).attr('docId') + '][docTitle=' + $(this).attr('docTitle') + ']',
            borderSize: '0',
            docId: $(this).attr('docId'),
            docTitle: $(this).attr('docTitle'),
            functionCallOnClose: function() { $('#pop-wrap .validation-message').hide(); },
            functionCallOnOpen: function() { $('#pop-wrap .name').focus().val($(this).attr('docTitle')); },
            isFolder: $(this).attr('isFolder') == 'true',
            modal: 1,
            overlayOpacity: '50',
            positionLeft: ((width - 60) * -1),
            positionTop: -25,
            positionType: 'anchoredSingleWindow',
            windowBGColor: 'transparent',
            windowPadding: 0,
            windowSourceID: '#pop'
        };

        $('#pop-content h2').text(settings.isFolder ? 'Rename Folder:' : 'Rename File:');

        $.openDOMWindow(settings);
        return false;
    });

    $('#pop-wrap .save').live('click', function() {
        if ($('#pop-wrap .name').val() != settings.docTitle) {
            $('#pop-wrap .validation-message').hide();
            var data = {
                operationType: 'RenameFileOrFolder',
                itemId: settings.docId,
                name: $('#pop-wrap .name').val()
            }
            MoveRenameFileOrFolder(data);
        }
    });

    $('#pop-wrap .name').live('keydown', function(e) {
        if (e.keyCode == '13') {
            e.preventDefault();
            $('#pop-wrap .save').click();
        }
    });
}

InitFilter = function() {
    $('.show-filter').click(function() {
        var settings = {
            anchoredSelector: '.actionbar',
            borderSize: '0',
            overlay: 1,
            overlayOpacity: 50,
            positionLeft: -25,
            positionTop: -15,
            positionType: 'anchoredSingleWindow',
            windowBGColor: 'transparent',
            windowSourceID: '#pop'
        };
        $.openDOMWindow(settings);
        return false;
    });

    $.fn.GetChildClass = function() {
        return $('option[value=' + this.val() + ']', this).attr('ChildCssClass');
    }

    $.fn.IsIn = function(elements) {
        return elements.hasClass($(this).attr('class'));
    }

    var wrap = $('#pop-wrap');
    var all = $('select, input', wrap);
    var master = $('select.Field', wrap);
    var filters = master;

    $('select', wrap).live('change', function() {

        var me = $(this);

        if (me.hasClass('Field')) {
            filters = master;
            $('input', all).val('');
            $('select', all).not(master).each(function() { $(this).val($('option', this).eq(0).attr('value')); });
        }
        else
            $('option', me).each(function() { filters = filters.not($('.' + $(this).attr('ChildCssClass'))); });

        while (me.length > 0) {
            if (!me.IsIn(filters))
                filters = filters.add(me);
            me = $('.' + me.GetChildClass(), wrap);
        }

        all.not(filters.show()).hide();

        $('.validation-message', wrap).hide().text('');

        var width = 160;
        $('select:visible, input:visible', wrap).each(function() { width += $(this).width() + 5; });
        wrap.css({ 'width': width + 'px' });
        $('#DOMWindow').css({ 'width': width + 100 + 'px' });
    });

    $('.apply-filter', wrap).live('click', function() {
        var filterString = '?Field=' + master.val();
        $('select:visible, input:visible', wrap).not(master).each(function(i) {
            filterString += (i == 0 ? '&Value=' : ';') + $(this).attr('class') + ':' + $(this).val();
        });

        if (window.location.search != filterString) {
            window.location = window.location.pathname + filterString;
        } else {
            $('.validation-message', wrap).show().text('The filter combination you have selected is the same as the filter that is currently applied.');
        }
    });

    ParseFilterQueryString = function() {
        var search = window.location.search.length > 0 ? window.location.search.substring(1) : '';
        if (search != '') {
            var params = search.split("&");
            master.val(params[0].split('=')[1]);
            all.not(master).hide();

            var filter = params[1].split('=')[1];
            var values = filter.split(';');
            
            for (i = 0; i < values.length; i++) {
                var klass = values[i].split(':')[0];
                var value = values[i].split(':')[1];
                $('.' + klass).val(value);
            }
        }
    }

    $('.edit-filter').click(function() {
        ParseFilterQueryString();
        master.change();
        $('.show-filter').click();
    });

    $('.remove-filter').click(function() { window.location = window.location.pathname; });

    if (window.location.search.length > 0)
        ParseFilterQueryString();

    master.change();
}




InitLicenseType = function() {
    $('.jq_LicenseType').click(function(e) {
        if ($(e).target().length > 0 && $($(e).target()[0]).val() == 0) {
            $('.jq_InstanceCode').css('display', '');
            $('.jq_ServerCode').css('display', 'none');
        }
        else {
            $('.jq_InstanceCode').css('display', 'none');
            $('.jq_ServerCode').css('display', '');
        }
    }).click();
}


InitLookupADUserInformation = function() {
    $('.jq_UserLogin').blur(function(e) {
        LookupADUserInformation(e);
        return false;
    });
}


InitProfilePicture = function() {
    $('#attachments_input').MultiFile({
        STRING: {
            icon: '<img src="/_layouts/images/Kiiro/icon-attachment.gif" alt="Attachment" />'
        }
    });
}


InitProjectPlan = function() {
    $('#attachments_input').MultiFile({
        STRING: {
            icon: '<img src="/_layouts/images/Kiiro/icon-attachment.gif" alt="Attachment" />'
        }
    });
}


InitProjectSummaryNoteUpdate = function() {
    $('.textarea').keydown(function(e) {
        EnableUpdateProjectSummary(e);
    }).mousedown(function(e) {
        EnableUpdateProjectSummary(e);
    });

    $('.jq_button-update').click(function(e) {
        $(this).attr({ disabled: 'disabled', src: "/_layouts/images/Kiiro/button-save-disabled.png" });
        SaveProjectSummaryNote(e);
        return false;
    });
}

InitSandboxEnabled = function() {
    $('.jq_sandboxEnabled input').click(function() {
        if (this.checked) {
            $('.jq_sandboxNavText').css({ 'display': 'block' });
            $(this).parents('div.row').removeClass('borderless');
        }
        else {
            $('.jq_sandboxNavText').css({ 'display': 'none' });
            $(this).parents('div.row').addClass('borderless');
        }
    });

    var input = $('.jq_sandboxEnabled input')[0];

    if (input.checked) {
        $('.jq_sandboxNavText').css({ 'display': 'block' });
        $(input).parents('div.row').removeClass('borderless');
    }
    else {
        $('.jq_sandboxNavText').css({ 'display': 'none' });
        $(input).parents('div.row').addClass('borderless');
    }
}

InitSearchBox = function() {
    var searchDefault = "Search...";
    var searchBox = $('input[name=SearchString]');

    var urlString = unescape(window.location.href);
    var urlHasSearch = urlString.substring(1);

    var kValue = "";
    var kParam = "k";
    var regexS = "[\\?&]" + kParam + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(urlHasSearch);
    if (results == null)
        kValue = "";
    else
        kValue = results[0];

    if (urlHasSearch.indexOf('k=') != -1 && kValue != "&k=") {
        var searchString = urlHasSearch.substring(urlHasSearch.indexOf('k=') + 2, urlHasSearch.indexOf('&'));
        $('input[name=SearchString]').attr('value', searchString).focus();
    }
    else {
        $('input[name=SearchString]').attr('value', searchDefault);
    }

    $('input[name=SearchString]').focus(function(e) {
        if (urlHasSearch.indexOf('k=') != -1 && kValue != "&k=") {
            var searchString = urlHasSearch.substring(urlHasSearch.indexOf('k=') + 2, urlHasSearch.indexOf('&'));
            $('input[name=SearchString]').attr('value', searchString);
        }
        else {
            $('input[name=SearchString]').attr('value', '');
        }
    });

    $('input[name=SearchString]').blur(function(e) {
        if ($('input[name=SearchString]').attr('value') == '') {
            if (urlHasSearch.indexOf('k=') != -1 && kValue != "&k=") {
                var searchString = urlHasSearch.substring(urlHasSearch.indexOf('k=') + 2, urlHasSearch.indexOf('&'));
                $('input[name=SearchString]').attr('value', searchString);
            }
            else {
                $('input[name=SearchString]').attr('value', searchDefault);
            }
        }
    });

    $('.search input')
        .focus(function() { $(this).addClass('hasFocus'); })
        .blur(function() { $(this).removeClass('hasFocus'); });
}

InitSlider = function() {
    $('.slider').each(function(e) {
        var initialValue = $('.jq_percentage', $(this).prev()).text();
        $(this).slider({
            slide: function(e, ui) {
                $('.jq_percentage', $(this).prev()).html(ui.value);
            },
            stop: function(e, ui) {
                $('.jq_percentage', $(this).prev()).html(ui.value);
                EnableSave(e);
            },
            value: initialValue
        });
    });
}

InitTeamMemberCollection = function() {
    var teamMembers = $("#team-member-collection input").not($("#team-member-collection .jq_select-all input"));

    TeamMembersCollectionCheckChecked();
    teamMembers.click(TeamMembersCollectionCheckChecked);

    $(".jq_select-all input").click(function() {
        var checked_status = this.checked;

        $("#team-member-collection input").each(function() {
            if (this.disabled == false) {
                this.checked = checked_status;
            }
        });
    });
}

InitUserStatusUpdate = function() {
    $('.jq_new-status').keydown(function(e) {
        EnableUpdateUserStatus(e);
    }).mousedown(function(e) {
        EnableUpdateUserStatus(e);
    });

    $('.jq_button-update').click(function(e) {
        $(this).attr({ disabled: 'disabled', src: "/_layouts/images/Kiiro/button-save-disabled.png" });
        SaveUserStatusUpdate(e);
        return false;
    });
}

InitWorkItems = function() {

    InitSlider();

    $('.jq_status-textarea').keydown(function(e) {
        EnableSave(e);
    });

    $('.jq_issueStatus :radio').mousedown(function(e) {
        EnableSave(e);
    });

    $('.jq_button-save').click(function(e) {
        $(this).attr({ disabled: 'disabled', src: "/_layouts/images/Kiiro/button-save-disabled.png" });
        SaveWorkItem(e);
        return false;
    });

    $('.jq_update-time').click(function(e) {
        var parentRow = $(e).target().parents('tr');
        $(parentRow).next().find('.slider').hide();

        if ($(parentRow).hasClass('open')) {
            // CLOSING   
            // slide row first then toggle class
            $(parentRow).next().find('div.status-wrap').slideToggle(function() {
                $(parentRow).next().find('.slider').show();
                $(parentRow).toggleClass('open');
            });
        }
        else {
            // OPENING
            // toggle class first then slide row
            $(parentRow).toggleClass('open').next().find('div.status-wrap').slideToggle(function() {
                $(parentRow).next().find('.slider').show();
            });
        }

        return false;
    });
}

LookupADUserInformation = function(e) {
    var data = {
        operationType: 'LookupADUserInformation',
        userLogin: $('.jq_UserLogin').val()
    }

    $('#jq_LoadingADLookup').css({ 'display': 'block' });
    $(e).target().parents('.panel').find('.input, .radio, .checkbox').attr('disabled', 'disabled');
    $('.form-buttons .button').attr('disabled', 'disabled');

    $.ajax({
        type: 'POST',
        data: data,
        dataType: 'json',
        success: function(json) {
            if (json.Login != null && json.Login != "") {
                // SUCCESS!
                $('.jq_ADLoginMessage').text('');
            } else {
                // FAILURE! if the first name field exists on the page, it's a user, else a group
                var ADItemType = $('.jq_FirstName').length > 0 ? "user" : "group";
                $('.jq_ADLoginMessage').text('Could not find a matching domain ' + ADItemType + ' for the provided login name.');
            }
            $('.jq_UserLogin').val(json.Login);
            $('.jq_FirstName').val(json.FirstName);
            $('.jq_LastName').val(json.LastName);
            $('.jq_PhoneNumber').val(json.PhoneNumber);
            $('.jq_Company').val(json.Company);
            $('.jq_Title').val(json.Title);
            $('.jq_Email').val(json.Email);
        },
        error: function(a, b, c) {
            alert('Unexpected Ajax Error\n' + a + '\n' + b + '\n' + c);
        },
        complete: function(XMLHttpRequest, textStatus) {
            $('#jq_LoadingADLookup').css({ 'display': 'none' });
            $(e).target().parents('.panel').find('.input, .radio, .checkbox').removeAttr('disabled');
            $('.form-buttons .button').removeAttr('disabled');
        }
    });
}

MakeColorPicker = function(id, value) {
    $(id).ColorPicker({
        color: RGBtoHex($(value).css('background-color')),
        onShow: function(colpkr) {
            $(colpkr).fadeIn(0);
            return false;
        },
        onHide: function(colpkr) {
            $(colpkr).fadeOut(0);
            return false;
        },
        onChange: function(hsb, hex, rgb) {
            $(value).css('background-color', '#' + hex);
        }
    });
}

MoveRenameFileOrFolder = function(data) {
    $('#pop-wrap .ajax-loader').show();
    $('#pop-wrap .save').hide();
    $('#pop-wrap .destinations, #pop-wrap .name').attr('disabled', 'disabled');

    $.ajax({
        type: 'POST',
        data: data,
        dataType: 'json',
        success: function(json) {
            var titleMessage = fileMessage = '';

            $(json.TitleMessage).each(function(i) { titleMessage += json.TitleMessage[i].Message + '<br/>' });
            $(json.FileMessage).each(function(i) { fileMessage += json.FileMessage[i].Message + '<br/>' });

            if (titleMessage == '' && fileMessage == '') {
                if (data.operationType == 'MoveFileOrFolder')
                    window.location.href = window.location.pathname + "?RootFolder=" + encodeURI(data.destination);
                else
                    window.location.href = window.location.pathname + window.location.search;
            }
            else if (titleMessage != '') {
                $('#pop-wrap .ajax-loader').hide();
                $('#pop-wrap .save').show();
                $('#pop-wrap .validation-message').show().html(titleMessage);
            }
            else if (fileMessage != '') {
                $('.ajax-loader').hide();
                $('#pop-wrap .validation-message').show().html(fileMessage);
            }
        },
        error: function(a, b, c) {
            alert('Unexpected Ajax Error\n' + a + '\n' + b + '\n' + c);
        }
    });
}

RGBtoHex = function(rgb) {
    var hex = "#";

    if (rgb != null && rgb.toString().indexOf('r', 0) > -1) {
        var color = rgb.toString().split('(')[1];
        color = color.split(')')[0];

        var i = 0;
        for (i = 0; i < 3; i++) {
            var N = color.split(',')[i];
            N = parseInt(N);
            if (N == 0 || isNaN(N)) {
                N = "00";
            }
            N = Math.max(0, N);
            N = Math.min(N, 255);
            N = Math.round(N);
            hex = hex + "0123456789ABCDEF".charAt((N - N % 16) / 16) + "0123456789ABCDEF".charAt(N % 16);
        }
        return hex;
    }
    else {
        return rgb;
    }
}

SaveProjectSummaryNote = function(e) {
    var details = $(e).target().parents('div.project-status-update');

    var data = {
        operationType: 'SaveProjectSummaryNote',
        itemId: $('.jq_projectId', details).val(),
        statusNote: $('.textarea', details).val(),
        currentUser: $('.jq_current-user', details).val()
    }

    var html = $('<div class="jq_save-animation" style="float:left; margin-left:25px; padding-top:12px; width: 400px;"><img src="/_layouts/images/kiiro/ajaxprogress.gif"/></div>');
    $(e).target().after(html);

    $.ajax(
	{
	    type: 'POST',
	    data: data,
	    dataType: 'json',
	    success: function(json) {
	        var validationMessage = '';
	        $(json.ProjectStatusMessage).each(function(i) {
	            validationMessage += ((i > 0 ? '<br/>' : '') + json.ProjectStatusMessage[i]);
	        });
	        $('.validation-message', details).text(validationMessage);

	        if (validationMessage == '') {
	            displayText = 'Status note saved successfully';
	        } else {
	            displayText = 'Status note was not saved. ' + validationMessage;
	        }

	        $('.jq_save-animation', details).html('').text(displayText).animate({ opacity: 0 }, 2000, function(e) {
	            $('.jq_save-animation', details).remove();
	        });
	    },
	    error: function(a, b, c) {
	        $('.jq_save-animation', details).remove();
	        alert('Unexpected Ajax Error\n' + a + '\n' + b + '\n' + c);
	    }
	});
}

SaveUserStatusUpdate = function(e) {
    var details = $(e).target().parents('div.activity-update');

    var data = {
        operationType: 'SaveUserStatus',
        itemId: $('.jq_userId', details).val(),
        statusNote: $('.jq_new-status', details).val()
    }

    var html = $('<div class="jq_save-animation" style="float:left; margin-left:25px; padding-top:12px"><img src="/_layouts/images/kiiro/ajaxprogress.gif"/></div>');
    $(e).target().after(html);

    $.ajax(
	{
	    type: 'POST',
	    data: data,
	    dataType: 'json',
	    success: function(json) {
	        var validationMessage = '';
	        $(json.StatusNoteMessage).each(function(i) {
	            validationMessage += ((i > 0 ? '<br/>' : '') + json.StatusNoteMessage[i]);
	        });
	        $('.validation-message', details).text(validationMessage);

	        if (validationMessage == '') {
	            displayText = 'Status note saved successfully';
	        } else {
	            displayText = 'Status note was not saved. ' + validationMessage;
	        }

	        $('.jq_save-animation', details).html('').text(displayText).animate({ opacity: 0 }, 2000, function(e) {
	            $('.jq_save-animation', details).remove();
	        });
	    },
	    error: function(a, b, c) {
	        $('.jq_save-animation', details).remove();
	        alert('Unexpected Ajax Error\n' + a + '\n' + b + '\n' + c);
	    }
	});
}

SaveWorkItem = function(e) {
    var details = $(e).target().parents('div.status-wrap');
    var titleTarget = details.parents('td').parents('tr.status').prev();

    var data = {
        operationType: 'SaveWork',
        itemId: $('.jq_workItemId', details).val(),
        statusNote: $('.jq_status-textarea', details).val(),
        percentComplete: $('.jq_percentage', details).html(),
        issueStatus: $('.jq_issueStatus :checked', details).val(),
        projectSRU: $('.jq_projectSRU', details).val()
    }

    var html = $('<div class="jq_save-animation" style="float:left; margin-left:25px; padding-top:12px"><img src="/_layouts/images/kiiro/ajaxprogress.gif"/></div>');
    $(e).target().after(html);

    $.ajax(
	{
	    type: 'POST',
	    data: data,
	    dataType: 'json',
	    success: function(json) {
	        var validationMessage = '';
	        $(json.StatusNoteMessage).each(function(i) {
	            validationMessage += ((i > 0 ? '<br/>' : '') + json.StatusNoteMessage[i]);
	        });
	        $('.validation-message', details).text(validationMessage);

	        if (validationMessage == '') {
	            displayText = 'Status note saved successfully';

	            //added this code to make the completed image appear dynamically when status is 100% or status is closed (for issue)
	            if ($('.jq_percentage', details).html() == "100" || $('.jq_issueStatus :checked', details).val() == "5") {
	                $(titleTarget).children('td.title').children('a').after('<img class=\'jq_completed\' src=\'/_layouts/images/Kiiro/icon_activity_completed_transparent.gif\'/>');
	            } else {
	                $(titleTarget).children('td.title').children('img.jq_completed').remove();
	            }
	        } else {
	            displayText = 'Status note was not saved. ' + validationMessage;
	        }

	        $('.jq_save-animation', details).html('').text(displayText).animate({ opacity: 0 }, 2000, function(e) {
	            $('.jq_save-animation', details).remove();
	        });
	    },
	    error: function(a, b, c) {
	        $('.jq_save-animation', details).remove();
	        alert('Unexpected Ajax Error\n' + a + '\n' + b + '\n' + c);
	    }
	});
}


TeamMembersCollectionCheckChecked = function() {
    var countChecked = 0;
    var countCheckBoxes = 0;
    var $teamMembers = $("#team-member-collection input").not($("#team-member-collection .jq_select-all input"));

    $teamMembers.each(function() {
        if (this.disabled == false) {
            countCheckBoxes++;
            if (this.checked) {
                countChecked++;
            }
        }
    });
    if (countCheckBoxes == countChecked) {
        $("#team-member-collection .jq_select-all input").attr('checked', true);
    }
    if (countCheckBoxes != countChecked) {
        $("#team-member-collection .jq_select-all input").attr('checked', false);
    }
}